package com.qnzw.zjmy.wxapi;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;

import com.android.volley.Request;
import com.qnzw.zjmy.refresh.init.GameApplication;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.qnzw.zjmy.R;
import com.qnzw.zjmy.config.UrlConfig;
import com.qnzw.zjmy.home.ui.activity.SplashGmActivity;
import com.qnzw.zjmy.home.ui.activity.WebViewActivity;
import com.qnzw.zjmy.home.ui.enums.RedisEnum;
import com.qnzw.zjmy.home.ui.model.User;
import com.qnzw.zjmy.home.ui.model.vo.RegisterVo;
import com.qnzw.zjmy.utils.ViewUtils;
import com.qnzw.zjmy.utils.risk.DeviceUtils;
import com.qnzw.zjmy.volley.BaseActivity;
import com.qnzw.zjmy.volley.state.HUCState;

import org.json.JSONException;
import org.json.JSONObject;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

public class WXEntryActivity extends BaseActivity implements IWXAPIEventHandler {
    public static String TAG = "MainActivity";

    private CheckBox checkBox;

    //微信授权登录
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String someValue = bundle.getString("response", "");
            // 继续处理
            if (!TextUtils.isEmpty(someValue)) {
                ViewUtils.showRisk(this, someValue, getSharedPreferences(RedisEnum.APP_QQ_CUSTOMER_SERVICE.getKey()));
            }
        }
    }

    @Override
    public void initView() {
        super.initView();
        checkBox = findViewById(R.id.cb_ok);
    }

    @Override
    public void initClick() {
        findViewById(R.id.tv_user_agreement).setOnClickListener(this);
        findViewById(R.id.tv_privacy_policy).setOnClickListener(this);
        findViewById(R.id.but_login).setOnClickListener(this);
        findViewById(R.id.but_DeviceLogin).setOnClickListener(this);
    }

    @Override
    public void initUtils() {
        super.initUtils();
        String wxAppId = getSharedPreferences(RedisEnum.WX_LOGIN_APP_ID.getKey());
        String wxAppIdSecret = getSharedPreferences(RedisEnum.WX_LOGIN_APP_SECRET.getKey());
        if (StrUtil.isNotEmpty(wxAppId) && StrUtil.isNotEmpty(wxAppIdSecret)) {
            //给IWXAPI赋值，第二个参数是AppID
            api = WXAPIFactory.createWXAPI(this, wxAppId, false);
            //注册到微信，参数是AppID
            api.registerApp(wxAppId);

            //这个必须加上，否则回调显示会出问题
            api.handleIntent(getIntent(), this);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.but_DeviceLogin:
                if (!checkBox.isChecked()) {
                    showToast("请已读并同意《用户协议》和《隐私政策》");
                    return;
                }
                login("");
                break;
            case R.id.tv_user_agreement:
                sendIntent(this, WebViewActivity.class, "用户协议");
                break;
            case R.id.tv_privacy_policy:
                sendIntent(this, WebViewActivity.class, "隐私政策");
                break;
            case R.id.but_login:
                if (!checkBox.isChecked()) {
                    showToast("请已读并同意《用户协议》和《隐私政策》");
                    return;
                }
                String RISK_WX_LOGIN_OPEN_APP = getSharedPreferences(RedisEnum.RISK_WX_LOGIN_OPEN_APP.getKey());

                String wxAppId = getSharedPreferences(RedisEnum.WX_LOGIN_APP_ID.getKey());
                String wxAppIdSecret = getSharedPreferences(RedisEnum.WX_LOGIN_APP_SECRET.getKey());
                if ((StrUtil.isNotEmpty(wxAppId) && StrUtil.isNotEmpty(wxAppIdSecret)) && RISK_WX_LOGIN_OPEN_APP.equals("1")) {
                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = wxAppId;
                    api.sendReq(req);
                } else {
                    login(RedisEnum.WX_LOGIN_APP_ID.getKey());
                }

                break;
            default:
        }
    }


    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_1:
                loadDismiss();
//                if (!(response instanceof User)) {
//                    showToast(response.toString());
//                    return;
//                }
//                User users = (User) response;
                try {
                    JSONObject object = new JSONObject(response.toString());
                    GameApplication.getMyApplication().token = object.optString("token");
                    SharedPreferences et = GameApplication.getMyApplication().getSharedPreferences("Token", MODE_PRIVATE);
                    SharedPreferences.Editor editor = et.edit();
                    editor.putString("token", GameApplication.getMyApplication().token);
                    editor.commit();
                    JSONObject user = object.getJSONObject("user");
                    setSharedPreferences("deviceId", user.optString("openid") + user.optString("deviceId"));
                    setSharedPreferences("loginTime", user.optString("loginTime"));
                    setSharedPreferences("usParentId", user.optString("usParentId"));
                    setSharedPreferences("id", user.optString("id"));
                    setSharedPreferences("signInNumber", user.optString("signInNumber"));
                    setSharedPreferences("signIdDayNumber", user.optString("signIdDayNumber"));
                    if (!user.optString("afbName").equals("null") || user.optString("afbName").isEmpty()) {
                        setSharedPreferences("afbName", user.optString("afbName"));
                        setSharedPreferences("afbPhone", user.optString("afbPhone"));
                    }
                    setSharedPreferences("code", user.optString("code"));
                    setSharedPreferences("moneyRedPacket", user.optString("moneyRedPacket"));
                    setSharedPreferences("moneyGoldCoin", user.optString("moneyGoldCoin"));
                    setSharedPreferences("nickname", user.optString("nickname"));
                    String index = getSharedPreferences("currentSubject");
                    setSharedPreferences("currentSubject", StrUtil.isNotEmpty(index) ? index : "0");
                    setSharedPreferences(RedisEnum.RISK_ADVERTISING_COINS.getKey(), user.optString("risk_advertising_coins"));
                    setSharedPreferences(RedisEnum.RISK_ADVERTISING_COINS_THAN_EQUAL.getKey(), user.optString("risk_advertising_coins_than_equal"));
                    setSharedPreferences(RedisEnum.RISK_ADVERTISING_COINS_THAN_EQUAL_TWO.getKey(), user.optString("risk_advertising_coins_than_equal_two"));
                    setSharedPreferences(RedisEnum.RISK_WHITE_LIST.getKey(), user.optString("risk_white_list"));
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

//                sendIntent(this, WebGameActivity.class);
                sendIntent(this, SplashGmActivity.class);
                finish();
                break;
        }
    }

    /**
     * 获取剪切板的内容
     *
     * @return
     */
    private String getClipboard() {
        // 获取剪切板管理器
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

        // 检查剪切板是否有内容
        if (clipboard.hasPrimaryClip()) {
            ClipData clip = clipboard.getPrimaryClip();
            // 获取剪切板中第一项的内容
            if (clip != null && clip.getItemCount() > 0) {
                CharSequence text = clip.getItemAt(0).getText();
                if (text != null) {
                    // 这里你有了剪切板的文本内容
                    String clipboardContent = text.toString();
                    if (TextUtils.isEmpty(clipboardContent)) {
                        return null;
                    }
                    try {
                        JSONObject jsonObject = new JSONObject(clipboardContent);
                        return jsonObject.getString("pid");
                    } catch (JSONException e) {
                        return null;
                    }
                }
            }
        }
        return null;
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    public void onReq(BaseReq baseReq) {
        System.out.println("Code值=" + JSONUtil.toJsonStr(baseReq));
    }

    @Override
    public void onResp(BaseResp baseResp) {
        Log.i(TAG, "Code值=" + JSONUtil.toJsonStr(baseResp));
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK: //点击确定登录
                String code = JSONUtil.parseObj(JSONUtil.toJsonStr(baseResp)).getStr("code");
                login(code);
                break;
            default:
                //点击的取消，根据自身业务处理
                break;
        }
    }

    private void login(String wxCode) {
        //获取网络数据
        RegisterVo registerVo = new RegisterVo();
        String oaid = DeviceUtils.getInstance().getOaId(this);

        // Log.e("测试------", "--------oaid: " +oaid);

        setSharedPreferences(RedisEnum.OAID.getKey(), oaid);

        registerVo.setOaid(oaid);
        registerVo.setWxCode(wxCode);
        registerVo.setDeviceId(getMyUUID());
        String code = getClipboard();
        Log.i(TAG, "剪贴板内容===================================" + code);

        registerVo.setCode(code);
        Long firstInstallTime = DeviceUtils.getInstance().getLastLoginTimeByPackageName(this, "com.tencent.mm");
        registerVo.setFirstInstallTime(String.valueOf(firstInstallTime));
        String url = UrlConfig.LOGIN_URL2;
        if (wxCode.equals(RedisEnum.WX_LOGIN_APP_ID.getKey())) {
            url = UrlConfig.LOGIN_URL;
        }
        hucRequestInterfase.executeStr(this, User.class, HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, url, hucParameInterfase.getRequestParameter(registerVo), true);
        loading();
    }


    private String getMyUUID() {
        final String androidId = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
        return androidId;
    }

}
